package cn.iocoder.yudao.module.product.service.stockoutin;

import cn.iocoder.yudao.module.product.dal.mysql.stockinfo.StockInfoMapper;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;

import cn.iocoder.yudao.module.product.controller.admin.stockoutin.vo.*;
import cn.iocoder.yudao.module.product.dal.dataobject.stockoutin.StockOutInDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.product.dal.mysql.stockoutin.StockOutInMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.product.enums.ErrorCodeConstants.*;

/**
 * 库存操作 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
public class StockOutInServiceImpl implements StockOutInService {

    @Resource
    private StockOutInMapper stockOutInMapper;

    @Resource
    private StockInfoMapper stockInfoMapper;

    @Override
    public Long createStockOutIn(StockOutInSaveReqVO createReqVO) {
        // 插入
        StockOutInDO stockOutIn = BeanUtils.toBean(createReqVO, StockOutInDO.class);
        stockOutInMapper.insert(stockOutIn);
        // 入库操作
        if (null != createReqVO.getInOwnerType()) {
            //使用乐观锁步骤：1先查询版本 2,更新版本+1 where （查询原版本）


        }


        // 返回
        return stockOutIn.getId();
    }

    @Override
    public void updateStockOutIn(StockOutInSaveReqVO updateReqVO) {
        // 校验存在
        validateStockOutInExists(updateReqVO.getId());
        // 更新
        StockOutInDO updateObj = BeanUtils.toBean(updateReqVO, StockOutInDO.class);
        stockOutInMapper.updateById(updateObj);
    }

    @Override
    public void deleteStockOutIn(Long id) {
        // 校验存在
        validateStockOutInExists(id);
        // 删除
        stockOutInMapper.deleteById(id);
    }

    private void validateStockOutInExists(Long id) {
        if (stockOutInMapper.selectById(id) == null) {
            throw exception(STOCK_OUT_IN_NOT_EXISTS);
        }
    }

    @Override
    public StockOutInDO getStockOutIn(Long id) {
        return stockOutInMapper.selectById(id);
    }

    @Override
    public PageResult<StockOutInDO> getStockOutInPage(StockOutInPageReqVO pageReqVO) {
        return stockOutInMapper.selectPage(pageReqVO);
    }

}